package com.yl.routeing.controller;

import com.yl.routeing.config.Coordinate;
import com.yl.routeing.config.ResultData;
import com.yl.routeing.service.MinStepCalculateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class MinStepCalculateController {

    @Autowired
    private MinStepCalculateService minStepCalculateService;

    //http://127.0.0.1:8080/minstep/route?lat1=104.021606&lon1=30.63031&lat2=104.072098&lon2=30.675159
    //http://127.0.0.1:8080/minstep/route?lat1=30.63031&lon1=104.021606&lat2=30.675159&lon2=104.072098
    @GetMapping(value = "/route", produces = "application/json")
    public ResultData minStepCalc(@RequestParam("lat1") String lat1, @RequestParam("lon1") String lon1,
                                  @RequestParam("lat2") String lat2, @RequestParam("lon2") String lon2) {
        ResultData data = new ResultData();
        double fromLat, fromLon, toLat, toLon;
        if (StringUtils.isEmpty(lat1) || StringUtils.isEmpty(lon1)
                || StringUtils.isEmpty(lat2) || StringUtils.isEmpty(lon2)) {
            data.setMsg("起点或终点经纬度不能为空！").setCode(500);
            return data;
        }
        try {
            try {
                fromLat = Double.valueOf(lat1);
                fromLon = Double.valueOf(lon1);
                toLat = Double.valueOf(lat2);
                toLon = Double.valueOf(lon2);
            } catch (NumberFormatException nfe) {
                data.setCode(500).setMsg(nfe.getMessage());
                return data;
            }
            List<Coordinate> routing = minStepCalculateService.routing(fromLat, fromLon, toLat, toLon);
            data.setCode(200).setMsg("OK").setResults(routing);
        } catch (Exception e) {
            data.setCode(500).setMsg(e.getMessage());
        }
        return data;
    }

}
